﻿using log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Serialization;

namespace FreeDream.Common.Other
{
    public class SettingConfig
    {
        private static readonly ILog logger = LogManager.GetLogger(typeof(SettingConfig));
        public SettingConfig() { }

        public string GetFileString(string fileName)
        {
            string strRes = string.Empty;
            try
            {
                if (string.IsNullOrWhiteSpace(fileName))
                {
                    return strRes;
                }
                //硬件配置 HardwareConfig devConfig
                string devPath = string.Format("{0}\\Config\\{1}", AppDomain.CurrentDomain.BaseDirectory, fileName);
                if (!File.Exists(devPath))
                {
                    return strRes;
                }
                strRes = File.ReadAllText(devPath);

            }
            catch (Exception ex)
            {
                logger.Error("SettingConfig GetFileString ..", ex);
            }

            return strRes;
        }

        /// <summary>
        /// 读取Xml文件类
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public T GetConfig<T>(string fileName)
        {
            try
            {
                var strRes = GetFileString(fileName);
                if (string.IsNullOrWhiteSpace(strRes))
                {
                    return default(T);
                }
                using (var str = new StringReader(strRes))
                {
                    var xmlSerializer = new XmlSerializer(typeof(T));
                    return (T)xmlSerializer.Deserialize(str);
                }
            }
            catch (Exception ex)
            {
                logger.Error("SettingConfig GetConfig ..", ex);
            }

            return default(T);
        }
    }
}
